<template>
  <div class="article-container">
    <van-nav-bar
      title="文章详情"
      class="page-nav-bar"
      left-arrow
      @click-left="$router.back()"
    />
    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>

<div class="article-wrap">
 <h1 class="title">{{ article.title }}</h1>
      <van-cell center class="userInfo">
        <div slot="title" class="name">{{ article.aut_name }}</div>
        <van-image
          slot="icon"
          class="avatar"
          round
          fit="cover"
          :src="article.aut_photo"
        />
        <div slot="label" class="pubdate">
          {{ article.pubdate | relativeTime }}
        </div>
        <van-button
          :icon="article.is_followed ? '' : 'plus'"
          class="follow-btn"
          :type="article.is_followed ? 'default' : 'info'"
          round
          size="small"
          @click="onFollow"
          :loading="isFollowLoading"
          >{{ article.is_followed ? "已关注" : "关注" }}</van-button
        >
      </van-cell>
      

      <div
        ref="articleContent"
        class="markdown-body"
        v-html="article.content"
      ></div>
      <!--文章列表-->
<commentList :source="this.articleId"/>
</div>
     
 

       
      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>

    <!-- 底部区域 -->
    <div class="article-bottom">
      <van-button class="comment-btn" type="default" round size="small"
        >写评论</van-button
      >
      <van-icon name="comment-o" info="123" color="#777" />
      <van-icon
        :color="article.is_collected ? 'yellow' : '#777'"
        :name="article.is_collected ? 'star' : 'star-o'"
        @click="onCollected"
      />
      <van-icon
        :color="article.attitude === 1 ? 'red' : '#777'"
        :name="article.attitude === 1 ? 'good-job' : 'good-job-o'"
        @click="onLike"
      />
      <van-icon name="share" color="#777777"></van-icon>
    </div>
  </div>
</template>

<script>
// 在组件中获取动态路由参数
// 方式一：this.$route.params.xxx
// 方式二：props 传参，推荐  映射到props里，也有一个articleId
import "./github-markdown.css";
import { getArticles } from "../api/article";
import { ImagePreview } from "vant";
import { addFollow, deleteFollow } from "../api/user.js";
import { addCollect, deleteCollect, addLike, deleteLike } from "../api/article";
import commentList from './commentList.vue'
// ImagePreview([
//   "https://img01.yzcdn.cn/vant/apple-1.jpg",
//   "https://img01.yzcdn.cn/vant/apple-2.jpg"
// ]);

export default {
  name: "neirong",
  data() {
    return {
      article: {}, //文章数据对象
      isFollowLoading: false, //关注用户的loading状态
      isCollectLoading: false //收藏的 loading状态
    };
  },
  components:{
      commentList
  },
  props: {
    articleId: {
      type: [String, Number, Object],
      required: true
    }
  },
  created() {
    this.loadArticle();
  },
  methods: {
    async loadArticle() {
      const { data: res } = await getArticles(this.articleId);
      console.log(res.data);
      this.article = res.data;

      //   数据改变影响视图更新（操作dom）不是立即的
      //   要马上渲染放到nextTick中
      // 得到所有的img标签
      this.$nextTick(() => {
        //   调用一个方法
        this.handelPerviewImage();
      });
      // 循环img列表，给img注册点击事件
      // 在事件处理函数中调用ImagePreview() 预览
    },
    handelPerviewImage() {
      // 获取文章内容DOM容器
      const article = this.$refs["articleContent"];
      console.log(article);
      //   获得所有图片
      const imgs = article.querySelectorAll("img");
      console.log(imgs);
      const imgPaths = [];
      // 获取图片预览
      imgs.forEach((img, index) => {
        // 把图片push到数组中
        imgPaths.push(img.src);
        img.onclick = function() {
          ImagePreview({
            images: imgPaths, //预览图片位置
            startPosition: index //起始位置
          });
        };
      });
    },
    async onFollow() {
      // 网络慢的时候关注时防止连续点击
      this.isFollowLoading = true;

      if (this.article.is_followed) {
        // 已关注，取消关注
        await deleteFollow({ userId: this.article.aut_id });
        // this.article.is_followed = false
      } else {
        // 没有关注，添加关注
        await addFollow({ userId: this.article.aut_id });
        // this.article.is_followed = true
      }
      // 更新视图
      this.article.is_followed = !this.article.is_followed;

      this.isFollowLoading = false;
    },
    async onCollected() {
      //   this.isCollectLoading = true;

      this.$toast.loading({
        message: "操作中...",
        forbidClick: true //禁止背景点击
      });
      if (this.article.is_collected) {
        // 已收藏，取消收藏
        await deleteCollect(this.articleId);
        // this.article.is_followed = false
      } else {
        // 没有收藏，添加收藏
        await addCollect(this.articleId);
        // this.article.is_followed = true
      }
      // 更新视图
      this.article.is_collected = !this.article.is_collected;

      //   this.isCollectLoading = false;

      this.$toast.success(`${this.article.is_collected ? "" : "取消"}收藏成功`);
    },
    async onLike() {
      this.$toast.loading({
        message: "操作中...",
        forbidClick: true //禁止背景点击
      });
      if (this.article.attitude === 1) {
        // 已点赞，取消点赞
        await deleteLike(this.articleId);
        this.article.attitude = -1;
      } else {
        // 没有点赞，添加点赞
        await addLike(this.articleId);
        this.article.attitude = 1;
      }
      // 更新视图

      this.$toast.success(
        `${this.article.attitude === 1 ? "" : "取消"}点赞成功`
      );
    },
  }
};
</script>
<style scoped lang="less">

.article-wrap{
    position:fixed;
    left:0;
    right:0;
    top:46px;
    bottom:44px;
    overflow-y:auto;
}
.title {
  font-size: 20px;
  color: #3a3a3a;
  padding: 14px;
  background-color: #fff;
  margin: 0;
}
.userInfo {
  .avatar {
    width: 35px;
    height: 35px;
    margin-right: 8px;
  }
  .name {
    font-size: 12px;
    color: #333333;
  }
  .pubdate {
    font-size: 11px;
    color: #b4b4b4;
  }
  .follow-btn {
    width: 85px;
    height: 25px;
  }
}

ul {
  list-style: unset;
}
.markdown-body {
  padding: 14px;
  background-color: #fff;
}

.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-content {
    padding: 55px 32px;
    /deep/ p {
      text-align: justify;
    }
  }
}

.loading-wrap {
  padding: 200px 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
}

.error-wrap {
  padding: 200px 32px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  .van-icon {
    font-size: 122px;
    color: #b4b4b4;
  }
  .text {
    font-size: 30px;
    color: #666666;
    margin: 33px 0 46px;
  }
  .retry-btn {
    width: 280px;
    height: 70px;
    line-height: 70px;
    border: 1px solid #c3c3c3;
    font-size: 30px;
    color: #666666;
  }
}

.article-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-sizing: border-box;
  height: 44px;
  border-top: 1px solid #d8d8d8;
  background-color: #fff;
  .comment-btn {
    width: 141px;
    height: 23px;
    border: 1px solid #eeeeee;
    font-size: 15px;
    line-height: 23px;
    color: #a7a7a7;
  }
  .van-icon {
    font-size: 20px;
    .van-info {
      font-size: 11px;
      background-color: #e22829;
    }
  }
}
</style>
